//
//  Mytools.m
//  7UGame
//
//  Created by 111 on 2017/2/14.
//  Copyright © 2017年 111. All rights reserved.
//

#import "Mytools.h"
#import <CommonCrypto/CommonDigest.h>


@implementation Mytools

+(BOOL) verifyURL:(NSString *)url{
    NSString *pattern = @"^(((http[s]{0,1}|ftp|Http[s]{0,1})://)?[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)|(www.[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)";
    
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:url];
    return isMatch;
}

+(NSString *)getMD5code:(NSString *)pswStr{
    NSString *resultStr = nil;//加密后的结果
    const char *cStr = [pswStr UTF8String];//指针不能变，cStr指针变量本身可以变化
    unsigned char result[16];
    CC_MD5(cStr, (unsigned int)strlen(cStr), result);
    resultStr = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
                 result[0], result[1], result[2], result[3],
                 result[4], result[5], result[6], result[7],
                 result[8], result[9], result[10], result[11],
                 result[12], result[13], result[14], result[15]
                 ];
    return resultStr;
}
+(NSString*)getCurrentTimestamp{
    //获取系统当前的时间戳
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
//    NSDate * dat = [self getBeiJingTime];
    NSTimeInterval a=[dat timeIntervalSince1970];
    NSInteger newA = a;
    NSString * timeString = [NSString stringWithFormat:@"%ld", (long)newA];
    return timeString;
}
+ (NSString *)timeStampTotime:(NSString *)timeString
{
    // 格式化时间
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    formatter.timeZone = [NSTimeZone timeZoneWithName:@"shanghai"];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSDate* date =[NSDate dateWithTimeIntervalSince1970:[timeString doubleValue]];
    NSString* dateString = [formatter stringFromDate:date];
    return dateString;
}
+(NSDate *)getCurrentDate{
    //以下为准确时间
    NSDate *date = [NSDate date];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate: date];
    NSDate *localeDate = [date  dateByAddingTimeInterval: interval];
    return localeDate;
}
+(NSString*)gotoWebView:(NSString * )str
{
    NSString * urlStart = @"https://m.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&rsv_idx=1&tn=baidu&wd=";
    NSString * urlEnd = @"&rsv_pq=80c7023000194588&rsv_t=e923%2BJi6SI0Q7Kl1q1%2BUl%2Bq7jbwN0GzkIghhykTbOJO0WX2%2BnR6iKTwQWLI&rsv_enter=1&inputT=7275&rsv_sug3=20&rsv_sug1=19&rsv_sug2=0&rsv_sug4=7642";
    NSMutableString * url = [[NSMutableString alloc]init];
    //URL 不能包含 ASCII 字符集,这样的字符进行转义的字符
    str = [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    [url appendString:urlStart];
    [url appendString:str];
    [url appendString:urlEnd];
    return url;
}

+(NSString*)encodeString:(NSString*)unencodedString{
    NSString * encodedStr = (NSString*) CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)unencodedString,NULL,(CFStringRef)@"!*'();:@&=+$,/?%#[]",kCFStringEncodingUTF8));
    return encodedStr;
}

//字符串转日期
+(NSDate*)dateStrToDate:(NSString *)dateStr{
    NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date =[dateFormat dateFromString:dateStr];
    NSDate *date2 = [date dateByAddingTimeInterval:8 * 60 * 60];
    return date2;
}
+(NSDate*)dateStrToDate:(NSString *)dateStr withFormat:(NSString*)format{
    NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:[NSString stringWithFormat:@"yyyy-%@ 00:00:00",format]];
    NSDate *date =[dateFormat dateFromString:dateStr];
    NSDate *date2 = [date dateByAddingTimeInterval:8 * 60 * 60];
    return date2;
}
+(NSString *)dateToDateStr:(NSDate*)date{
    NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date2 = [date dateByAddingTimeInterval:-8 * 60 * 60];
    NSString *currentDateStr = [dateFormat stringFromDate:date2];
    return currentDateStr;
}
+(NSString*)dateTopString:(NSDate*)date{
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy年MM月dd日HH时mm分"];
    NSString *strDate = [dateFormatter stringFromDate:date];
    return strDate;
}
+(NSDate*)stringToDate:(NSString*)string{
    
    NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy年MM月dd日HH时mm分"];
    NSDate *date =[dateFormat dateFromString:string];
    return date;
}
+(void)drawDashLine:(UIView *)drawView dashCenter:(CGPoint)dashCenter startPoint:(CGPoint)sP endPoint:(CGPoint)eP lineWidth:(CGFloat)lineWidth{
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    [shapeLayer setBounds:drawView.bounds];
    [shapeLayer setPosition:dashCenter];
    [shapeLayer setFillColor:[[UIColor clearColor] CGColor]];
    [shapeLayer setStrokeColor:[[UIColor lightGrayColor] CGColor]];
    [shapeLayer setLineWidth:lineWidth];
    [shapeLayer setLineJoin:kCALineJoinRound];
    [shapeLayer setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithInt:5],[NSNumber numberWithInt:2], nil]];
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, sP.x, sP.y);
    CGPathAddLineToPoint(path, NULL, eP.x, eP.y);
    [shapeLayer setPath:path];
    CGPathRelease(path);
    [[drawView layer] addSublayer:shapeLayer];
}
+(NSString *)numberToMoneyFormatter:(long)num{
    NSNumberFormatter * formatter = [[NSNumberFormatter alloc]init];
    formatter.numberStyle = NSNumberFormatterDecimalStyle;
    NSString * newNumber = [formatter stringFromNumber:[NSNumber numberWithLong:num]];
    return newNumber;
}

//消息弹窗
+(void)warnText:(NSString *)str status:(NoticeType)typeP{
    dispatch_async(dispatch_get_main_queue(), ^{
        if (typeP == Common) {
            //感叹号
            [FTIndicator showInfoWithMessage:str userInteractionEnable:NO];
        }else if (typeP == Success){
            //success
            [FTIndicator showSuccessWithMessage:str];
        }else if(typeP == Toast){
            [FTIndicator showInfoWithMessage:str];
        }else{
            //error
            [FTIndicator showErrorWithMessage:str];
        }
    });
    
}
+(void)deleteAllUserDefaules{
    NSUserDefaults *defatluts = [NSUserDefaults standardUserDefaults];
    NSDictionary *dictionary = [defatluts dictionaryRepresentation];
    for(NSString *key in [dictionary allKeys]){
        if ([key isEqualToString:@"gesturelock"]==NO&&
            [key isEqualToString:@"username"]==NO&&
            [key isEqualToString:@"gestureFinalSaveKey"]==NO&&
            [key isEqualToString:@"firstLaunch"]==NO&&
            [key isEqualToString:@"gesturestate"]==NO&&
            [key isEqualToString:@"fingerstate"]==NO&&
            [key isEqualToString:@"currentVersion"]==NO&&
            [key isEqualToString:@"rememberPassword"]==NO&&
            [key isEqualToString:@"password"]==NO&&
            [key isEqualToString:@"MainDomain"]==NO&&
            [key isEqualToString:@"O2ODomain"]==NO&&
            [key isEqualToString:@"MergeCodeDomain"]==NO&&
            [key isEqualToString:@"orderid"]==NO&&[key isEqualToString:@"PeripheralDeviceName"]&&[key isEqualToString:@"token"]) {
            [defatluts removeObjectForKey:key];
            [defatluts synchronize];
        }
    }
}
+(NSString*)deleteSpaceInput:(NSString *)str{
    if ([str containsString:@" "]) {
        str = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    }
    return str;
}
#pragma mark json格式字符串转字典
+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    
    if (jsonString == nil) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

#pragma mark 字典转json格式字符串
+ (NSString*)dictionaryToJson:(NSDictionary *)dic
{
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}

#pragma mark 数组转json格式字符串
+ (NSString*)ArrtionaryToJson:(NSMutableArray *)arr
{
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}

/**验证是不是邮箱*/
+(BOOL)isEmail:(NSString *)email
{
    /**
     *  前半部分（由字母、数字和（.)、_ 、%、+、- 等符号组成）中间部分（由数字、字母组成和(.)、-等符号组成）最后部分(由 . 和数字组成，最少2个字符，最多四个字符)
     */
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}$";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    if ([emailTest evaluateWithObject:email]) {
        return YES;
    }
    else
    {
        return NO;
    }
}
/**验证是不是身份证号码*/
+(BOOL)isIdCardNum:(NSString *)IdCardNumber
{
    if (IdCardNumber.length != 18) {
        return NO;
    }
    //15位身份证为第一代身份证，在2013年就停止使用
    //身份证格式 18位数字组成 或者17位数字+xX
    NSString *idCardRegex = @"\\d{18}$|(\\d{17}[xX])$";
    NSPredicate *idCardTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", idCardRegex];
    if ([idCardTest evaluateWithObject:IdCardNumber]) {
        return YES;
    }
    else
    {
        return NO;
    }
}

//日期大小比较
+(int)compareOneDay:(NSDate *)oneDay withAnotherDay:(NSDate *)anotherDay{
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    //stringFromDate这个方法加了八小时
    NSString *oneDayStr = [dateFormatter stringFromDate:oneDay];
    NSString *anotherDayStr = [dateFormatter stringFromDate:anotherDay];
    //dateFromString这个方法减了八小时，这狗日的
    NSDate *dateA = [dateFormatter dateFromString:oneDayStr];
    NSDate *dateB = [dateFormatter dateFromString:anotherDayStr];
    NSComparisonResult result = [dateA compare:dateB];
//    NSLog(@"date1 : %@, date2 : %@", oneDay, anotherDay);
    if (result == NSOrderedDescending) {
        //NSLog(@"Date1  is in the future");
        return 1;
    }
    else if (result ==NSOrderedAscending){
        //NSLog(@"Date1 is in the past");
        return -1;
    }
    //NSLog(@"Both dates are the same");
    return 0;
    
}

+(BOOL)isPureInt:(NSString*)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    int val;
    return[scan scanInt:&val] && [scan isAtEnd];
}

+ (BOOL)isPureFloat:(NSString*)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    float val;
    return[scan scanFloat:&val] && [scan isAtEnd];
}

//银行卡
+(BOOL)validateBankCardNumber:(NSString *)bankCardNumber
{
    BOOL flag;
    if (bankCardNumber.length <= 0) {
        flag = NO;
        return flag;
    }
    NSString *regex2 = @"^(\\d{15,30})";
    NSPredicate *bankCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    return [bankCardPredicate evaluateWithObject:bankCardNumber];
}

//从字符串中获取数字
+(NSString *)getNumberForString:(NSString *)str{
    NSRegularExpression *regular = [NSRegularExpression regularExpressionWithPattern:@"[a-zA-Z.-./.(.)]" options:0 error:NULL];
    NSString *string = str;
    NSString *result = [regular stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:@""];
    return result;
    
}

//去掉utc时间
+ (NSString *)htcTimeToLocationStr:(NSString*)utcDate
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //输入格式
    [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
    NSTimeZone *localTimeZone = [NSTimeZone localTimeZone];
    [dateFormatter setTimeZone:localTimeZone];
    
    NSDate *dateFormatted = [dateFormatter dateFromString:utcDate];
    //输出格式
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dateString = [dateFormatter stringFromDate:dateFormatted];
    return dateString;
}
+(NSInteger)howManyDaysInThisYear:(NSInteger)year withMonth:(NSInteger)month{
    if((month == 1) || (month == 3) || (month == 5) || (month == 7) || (month == 8) || (month == 10) || (month == 12))
        return 31 ;
    if((month == 4) || (month == 6) || (month == 9) || (month == 11))
        return 30;
    if((year % 4 == 1) || (year % 4 == 2) || (year % 4 == 3)){
        return 28;
    }
    if(year % 400 == 0)
        return 29;
    if(year % 100 == 0)
        return 28;
    return 29;
}

+(UIColor*)mostColor:(UIImage*)image{
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_6_1
    int bitmapInfo = kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedLast;
#else
    int bitmapInfo = kCGImageAlphaPremultipliedLast;
#endif
    //第一步 先把图片缩小 加快计算速度. 但越小结果误差可能越大
    CGSize thumbSize=CGSizeMake(image.size.width, image.size.height);
    
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(NULL,
                                                 thumbSize.width,
                                                 thumbSize.height,
                                                 8,//bits per component
                                                 thumbSize.width*4,
                                                 colorSpace,
                                                 bitmapInfo);
    
    CGRect drawRect = CGRectMake(0, 0, thumbSize.width, thumbSize.height);
    CGContextDrawImage(context, drawRect, image.CGImage);
    CGColorSpaceRelease(colorSpace);
    
    //第二步 取每个点的像素值
    unsigned char* data = CGBitmapContextGetData (context);
    if (data == NULL) return nil;
    NSCountedSet *cls=[NSCountedSet setWithCapacity:thumbSize.width*thumbSize.height];
    
    for (int x=0; x<thumbSize.width; x++) {
        for (int y=0; y<thumbSize.height; y++) {
            int offset = 4*(x*y);
            int red = data[offset];
            int green = data[offset+1];
            int blue = data[offset+2];
            int alpha =  data[offset+3];
            if (alpha>0) {//去除透明
                if (red==255&&green==255&&blue==255) {//去除白色
                }else{
                    NSArray *clr=@[@(red),@(green),@(blue),@(alpha)];
                    [cls addObject:clr];
                }
                
            }
        }
    }
    CGContextRelease(context);
    //第三步 找到出现次数最多的那个颜色
    NSEnumerator *enumerator = [cls objectEnumerator];
    NSArray *curColor = nil;
    NSArray *MaxColor=nil;
    NSUInteger MaxCount=0;
    while ( (curColor = [enumerator nextObject]) != nil )
    {
        NSUInteger tmpCount = [cls countForObject:curColor];
        if ( tmpCount < MaxCount ) continue;
        MaxCount=tmpCount;
        MaxColor=curColor;
        
    }
    return [UIColor colorWithRed:([MaxColor[0] intValue]/255.0f) green:([MaxColor[1] intValue]/255.0f) blue:([MaxColor[2] intValue]/255.0f) alpha:0.75];//([MaxColor[3] intValue]/255.0f)
}
+(NSString*)returnDecimalNumStr:(NSString*)numStr{
    NSString *doubleString  = [NSString stringWithFormat:@"%lf", [numStr doubleValue]];
    NSDecimalNumber *decNumber = [NSDecimalNumber decimalNumberWithString:doubleString];
    return [decNumber stringValue];
}

+(BOOL)IsChinese:(NSString *)str {
    for(int i=0; i< [str length];i++){
        int a = [str characterAtIndex:i];
        if( a > 0x4e00 && a < 0x9fff){
            return YES;
        }        
    }
    return NO;
}
+(UIImage*)viewBecomeImage:(UIView*)v{
    CGSize s = v.bounds.size;
    // 下面方法，第一个参数表示区域大小。第二个参数表示是否是非透明的。如果需要显示半透明效果，需要传NO，否则传YES。第三个参数就是屏幕密度了
    UIGraphicsBeginImageContextWithOptions(s, NO, [UIScreen mainScreen].scale);
    [v.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage*image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}
+(NSString *)getMoneyFormat:(NSString*)money{
    if ([money containsString:@"￥"]) {
        money = [money stringByReplacingOccurrencesOfString:@"￥" withString:@""];
    }
    NSRange range = [money rangeOfString:@"."];    
    if (range.location == NSNotFound) {//没找到小数点就是整型或者非法字符
        BOOL isInt = [self isPureInt:money];
        if (money.length==0) {
            return @"";
        }
        if (!isInt) {
            [Mytools warnText:@"数字格式错误，请重输" status:Error];
            return @"";
        }
    }else{
        BOOL isFloat = [self isPureFloat:money];
        if (!isFloat) {
            [Mytools warnText:@"数字格式错误，请重输" status:Error];
            return @"";
        }else{//如果是浮点数，就判断是否是两位小数
            NSInteger floatLength = money.length - range.location - 1;
            if (floatLength>2) {
                return [money substringWithRange:NSMakeRange(0, range.location+3)];
            }
        }
    }
    return money;
}
//大于等于8.0   ps：currentUserNotificationSettings在iOS10 废弃
+ (BOOL)isUserNotificationEnable { // 判断用户是否允许接收通知
    BOOL isEnable = NO;
    UIUserNotificationSettings *setting = [[UIApplication sharedApplication] currentUserNotificationSettings];
    isEnable = (UIUserNotificationTypeNone == setting.types) ? NO : YES;
    return isEnable;
}
@end
